<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>AI Chat</title>

<style>
/* 整体布局 */
body {
    margin:0;
    padding:0;
    font-family: "Segoe UI", Arial, sans-serif;
    display:flex;
    height:100vh;
    background:#ececec;
}

/* 左侧侧边栏 */
.sidebar {
    width: 280px;
    background: #1f1f1f;
    color: #fff;
    padding: 20px 15px;
    overflow-y: auto;
    border-right: 1px solid #333;
}

.sidebar h2 {
    margin:0 0 15px 0;
    font-size:20px;
    font-weight:600;
    letter-spacing:1px;
    text-align:center;
}

/* 会话卡片 */
.record {
    background:#2c2c2c;
    padding:12px 10px;
    margin-bottom:12px;
    border-radius:8px;
    cursor:pointer;
    transition:0.2s;
    display:flex;
    justify-content:space-between;
    align-items:center;
}

.record span {
    color:#ddd;
    font-size:14px;
}

.record:hover {
    background:#3a3a3a;
}

/* 删除按钮 */
.delete-btn {
    background:#d9534f;
    color:white;
    border:none;
    border-radius:4px;
    padding:3px 8px;
    cursor:pointer;
    font-size:12px;
}

.delete-btn:hover {
    background:#c9302c;
}

/* 主聊天区域 */
.main {
    flex: 1;
    display:flex;
    flex-direction:column;
    background:#f6f6f6;
}

/* 聊天内容区域 */
#chatbox {
    flex: 1;
    padding:20px;
    overflow-y:auto;
}

/* 消息气泡 */
.msg {
    max-width:70%;
    padding:12px 15px;
    margin:12px 0;
    border-radius:12px;
    line-height:1.5;
    font-size:15px;
    box-shadow:0 2px 5px rgba(0,0,0,0.1);
}

.user {
    background:#dbe8ff;
    align-self:flex-end;
    border-left:4px solid #0077ff;
}

.ai {
    background:#e8ffe6;
    align-self:flex-start;
    border-left:4px solid #28a745;
}

.error {
    background:#ffe6e6;
    border-left:4px solid #d00;
}

/* 输入栏 */
.input-area {
    display:flex;
    padding:12px;
    background:#fff;
    border-top:1px solid #ddd;
    box-shadow:0 -2px 6px rgba(0,0,0,0.05);
}

input {
    flex:1;
    padding:12px;
    font-size:15px;
    border:1px solid #ccc;
    border-radius:8px;
    outline:none;
}

input:focus {
    border-color:#0077ff;
}

button {
    padding:12px 20px;
    margin-left:10px;
    background:#0077ff;
    color:white;
    border:none;
    border-radius:8px;
    cursor:pointer;
    font-size:15px;
}

button:hover {
    background:#005ec2;
}
</style>
</head>
<body>

<!-- 左侧历史记录栏 -->
<div class="sidebar">
    <h2>对话记录</h2>
    <div id="historyList"></div>
</div>

<!-- 右侧主界面 -->
<div class="main">
    <div id="chatbox"></div>

    <div class="input-area">
        <input id="userInput" type="text" placeholder="输入消息..." autocomplete="off">
        <button onclick="sendMsg()">发送</button>
    </div>
</div>

<script>
let currentSessionId = Date.now() + "";
let history = [];

// ===== 显示消息 =====
function showMessage(role, content) {
    const chatbox = document.getElementById("chatbox");
    const cls = (role === "user" ? "user" : "ai");
    const div = document.createElement("div");
    div.className = "msg " + cls;
    div.textContent = content;
    chatbox.appendChild(div);
    chatbox.scrollTop = chatbox.scrollHeight;
}

// ===== 保存（本地） =====
function saveLocalHistory() {
    let all = JSON.parse(localStorage.getItem("chatRecords") || "{}");
    all[currentSessionId] = history;
    localStorage.setItem("chatRecords", JSON.stringify(all));
}

// ===== 从服务器加载历史列表 =====
async function loadHistoryList() {
    const listDiv = document.getElementById("historyList");
    listDiv.innerHTML = "加载中...";

    const res = await fetch("load_history_list.php");
    const files = await res.json();

    listDiv.innerHTML = "";

    files.forEach(file => {
        let div = document.createElement("div");
        div.className = "record";

        div.innerHTML = `
            <span>${file}</span>
            <button class="delete-btn" onclick="event.stopPropagation(); deleteRecord('${file}')">X</button>
        `;

        div.onclick = () => loadSessionFromServer(file);
        listDiv.appendChild(div);
    });
}

// ===== 加载服务器对话内容 =====
async function loadSessionFromServer(file) {
    currentSessionId = file;

    const res = await fetch("load_history.php?session=" + file);
    history = await res.json();

    document.getElementById("chatbox").innerHTML = "";
    history.forEach(msg => showMessage(msg.role, msg.content));
}

// ===== 删除历史记录 =====
async function deleteRecord(file) {
    if (!confirm("确定要删除此对话吗？")) return;

    await fetch("delete_history.php", {
        method:"POST",
        headers:{ "Content-Type":"application/json" },
        body: JSON.stringify({ file })
    });

    loadHistoryList();
}

// ===== 发送消息 =====
async function sendMsg() {
    let input = document.getElementById("userInput");
    let text = input.value.trim();
    if (!text) return;

    showMessage("user", text);
    history.push({ role:"user", content:text });
    saveLocalHistory();
    input.value = "";

    // 调用后端 AI API
    const res = await fetch("chat_api.php", {
        method:"POST",
        headers:{ "Content-Type":"application/json" },
        body: JSON.stringify({ messages: history })
    });

    const reply = await res.json();

    const content = reply.choices[0].message.content;
    showMessage("ai", content);

    history.push({ role:"assistant", content });
    saveLocalHistory();
}

// ===== 页面加载后自动读取服务器记录 =====
window.onload = loadHistoryList;

// ===== 关闭网页时自动上传记录到服务器 =====
window.addEventListener("beforeunload", () => {
    let all = JSON.parse(localStorage.getItem("chatRecords") || "{}");

    fetch("save_history.php", {
        method:"POST",
        headers:{ "Content-Type":"application/json" },
        body: JSON.stringify(all)
    });
});
</script>

</body>
</html>
